package com.trace.demo.controller;

import com.trace.demo.entity.Product;
import com.trace.demo.entity.User;
import com.trace.demo.entity.SystemMessage;
import com.trace.demo.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 控制面板数据控制器
 * 提供控制面板所需的各种统计数据
 */
@RestController
@RequestMapping("/api/dashboard")
public class DashboardController {
    
    private static final Logger logger = LoggerFactory.getLogger(DashboardController.class);

    private final UserRepository userRepository;
    private final ProductRepository productRepository;
    private final SystemMessageRepository systemMessageRepository;
    
    // 可选的依赖
    private FarmingInfoRepository farmingInfoRepository;
    private TodoItemRepository todoItemRepository;
    private FarmingActivityRepository farmingActivityRepository;

    @Autowired
    public DashboardController(
            UserRepository userRepository,
            ProductRepository productRepository,
            SystemMessageRepository systemMessageRepository) {
        this.userRepository = userRepository;
        this.productRepository = productRepository;
        this.systemMessageRepository = systemMessageRepository;
        logger.info("DashboardController initialized with required dependencies");
    }
    
    @Autowired(required = false)
    public void setFarmingInfoRepository(FarmingInfoRepository farmingInfoRepository) {
        this.farmingInfoRepository = farmingInfoRepository;
        logger.info("FarmingInfoRepository injected");
    }
    
    @Autowired(required = false)
    public void setTodoItemRepository(TodoItemRepository todoItemRepository) {
        this.todoItemRepository = todoItemRepository;
        logger.info("TodoItemRepository injected");
    }
    
    @Autowired(required = false)
    public void setFarmingActivityRepository(FarmingActivityRepository farmingActivityRepository) {
        this.farmingActivityRepository = farmingActivityRepository;
        logger.info("FarmingActivityRepository injected");
    }

    /**
     * 获取仪表盘数据卡片信息
     */
    @GetMapping("/data-cards")
    public ResponseEntity<Map<String, Object>> getDataCards() {
        try {
            Map<String, Object> dataCards = new HashMap<>();

            // 总用户数
            dataCards.put("totalUsers", userRepository.count());

            // 总产品数
            dataCards.put("totalProducts", productRepository.count());

            // 今日新增用户
            LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
            LocalDateTime endOfDay = startOfDay.plusDays(1).minusNanos(1);
            dataCards.put("todayNewUsers", userRepository.countTodayNewUsers());

            // 今日新增产品
            dataCards.put("todayNewProducts", productRepository.countTodayNewProducts(startOfDay, endOfDay));

            // 待处理的待办事项
            if (todoItemRepository != null) {
                LocalDateTime now = LocalDateTime.now();
                dataCards.put("pendingTasks", todoItemRepository.countOverdueTodoItems(now));
            } else {
                dataCards.put("pendingTasks", 0);
            }

            // 总种植活动数
            if (farmingInfoRepository != null) {
                dataCards.put("totalFarmingInfo", farmingInfoRepository.count());
            } else {
                dataCards.put("totalFarmingInfo", 0);
            }

            return ResponseEntity.ok(dataCards);
        } catch (Exception e) {
            logger.error("Error fetching dashboard data cards", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 获取仪表盘数据卡片信息 (别名端点)
     */
    @GetMapping("/cards")
    public ResponseEntity<Map<String, Object>> getCards() {
        // 调用原有的方法复用逻辑
        return getDataCards();
    }

    /**
     * 获取用户角色分布
     */
    @GetMapping("/user-distribution")
    public ResponseEntity<Map<String, Object>> getUserRoleDistribution() {
        try {
            List<Object[]> roleStats = userRepository.countUsersByRole();
            Map<String, Object> distribution = new HashMap<>();

            // 确保即使数据库返回为空也有一个空数组
            List<Map<String, Object>> roles = new ArrayList<>();

            for (Object[] stat : roleStats) {
                Map<String, Object> roleMap = new HashMap<>();
                roleMap.put("role", stat[0]);
                roleMap.put("count", stat[1]);
                roles.add(roleMap);
            }

            // 将角色统计包装在一个roles键中返回
            distribution.put("roles", roles);

            return ResponseEntity.ok(distribution);
        } catch (Exception e) {
            logger.error("Error fetching user role distribution", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 获取近30天注册用户统计
     */
    @GetMapping("/registration-stats")
    public ResponseEntity<Map<String, Object>> getRegistrationStats() {
        try {
            // 获取近30天的日期
            LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);

            // 获取30天内注册的所有用户
            List<User> recentUsers = userRepository.findByCreatedAtAfter(thirtyDaysAgo);

            // 按日期分组统计
            Map<String, Long> dailyStats = new LinkedHashMap<String, Long>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

            // 初始化30天数据为0
            for (int i = 29; i >= 0; i--) {
                LocalDate date = LocalDate.now().minusDays(i);
                dailyStats.put(date.format(formatter), 0L);
            }

            // 统计每日注册人数
            for (User user : recentUsers) {
                String day = user.getCreatedAt().format(formatter);
                dailyStats.put(day, dailyStats.getOrDefault(day, 0L) + 1);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("lastThirtyDays", dailyStats);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching registration stats", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 获取最近的活动记录
     */
    @GetMapping("/recent-activities")
    public ResponseEntity<Map<String, Object>> getRecentActivities() {
        try {
            if (farmingActivityRepository == null) {
                return ResponseEntity.ok(Collections.singletonMap("activities", Collections.emptyList()));
            }
            
            // 获取最近10条活动记录
            List<Map<String, Object>> activities = farmingActivityRepository.findTop10ByOrderByTimestampDesc()
                .stream()
                .map(activity -> {
                    Map<String, Object> activityMap = new HashMap<>();
                    activityMap.put("id", activity.getId());
                    activityMap.put("userId", activity.getUser().getId());
                    activityMap.put("username", activity.getUser().getUsername());
                    activityMap.put("type", activity.getType());
                    activityMap.put("content", activity.getContent());
                    activityMap.put("timestamp", activity.getTimestamp());
                    return activityMap;
                })
                .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("activities", activities);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching recent activities", e);
            return ResponseEntity.ok(Collections.singletonMap("activities", Collections.emptyList()));
        }
    }

    /**
     * 获取系统消息
     */
    @GetMapping("/system-messages")
    public ResponseEntity<Map<String, Object>> getSystemMessages() {
        try {
            // 从数据库获取系统消息
            List<Map<String, Object>> messages = systemMessageRepository.findAll().stream()
                .map(message -> {
                    Map<String, Object> messageMap = new HashMap<>();
                    messageMap.put("id", message.getId());
                    messageMap.put("title", message.getTitle());
                    messageMap.put("content", message.getContent());
                    messageMap.put("type", message.getType());
                    return messageMap;
                })
                .collect(Collectors.toList());

            // 如果没有消息，添加默认消息
            if (messages.isEmpty()) {
                Map<String, Object> defaultMessage = new HashMap<>();
                defaultMessage.put("id", 1);
                defaultMessage.put("title", "系统欢迎");
                defaultMessage.put("content", "欢迎使用追溯系统");
                defaultMessage.put("type", "info");
                defaultMessage.put("timestamp", LocalDateTime.now());
                messages.add(defaultMessage);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("messages", messages);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching system messages", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 获取产品分类统计
     */
    @GetMapping("/product-categories")
    public ResponseEntity<Map<String, Object>> getProductCategories() {
        try {
            List<Map<String, Object>> categories = productRepository.countByCategories();
            Map<String, Object> result = new HashMap<>();
            result.put("categories", categories);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching product categories", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 获取近期产品统计
     */
    @GetMapping("/recent-products")
    public ResponseEntity<Map<String, Object>> getRecentProducts() {
        try {
            // 获取最近添加的5个产品
            List<Map<String, Object>> products = productRepository.findAll().stream()
                .sorted(Comparator.comparing(Product::getCreatedAt).reversed())
                .limit(5)
                .map(product -> {
                    Map<String, Object> productMap = new HashMap<>();
                    productMap.put("id", product.getId());
                    productMap.put("name", product.getProductName());
                    productMap.put("category", product.getCategory());
                    productMap.put("productCode", product.getProductCode());
                    productMap.put("createdAt", product.getCreatedAt());
                    return productMap;
                })
                .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("recentProducts", products);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching recent products", e);
            return ResponseEntity.internalServerError().body(Collections.singletonMap("error", e.getMessage()));
        }
    }
}
